import { _decorator, Component, instantiate, log, math, Node, Prefab, UITransform, view } from 'cc';
import { L } from './tools/L';
const { ccclass, property } = _decorator;

@ccclass('RewardManager')
export class RewardManager extends Component {
    @property
    rewardSpawnRate: number = 5;
    @property(Prefab)
    reward0Prefab: Prefab;

    @property(Prefab)
    reward1Prefab: Prefab;

    start() {
        this.schedule(() => {
            const randomInt = math.randomRangeInt(0, 5);
            let prefab = this.reward0Prefab;
            if(randomInt === 1) {
                prefab = this.reward1Prefab;
            }
            this.doSpawn(prefab)
        }, this.rewardSpawnRate);
    }

    protected onDestroy(): void {
        this.unscheduleAllCallbacks();
    }

    doSpawn(prefab: Prefab) {
        const newNode = instantiate(prefab);
        this.node.addChild(newNode);
        const contentSize = newNode.getComponent(UITransform).contentSize;
        let screenWidth = view.getVisibleSize().width;
        const randomX = math.randomRangeInt(-screenWidth / 2 + contentSize.width / 2, screenWidth / 2 - contentSize.width / 2);
        newNode.setPosition(randomX, view.getVisibleSize().height / 2 + contentSize.height / 2, this.node.getPosition().z);
        L.debug(`Reward[${newNode.name}] 新产生, 坐标:[ ${newNode.getPosition()} ]`);
    }
}

